package com.ncmmall.mall.controller.business.goods;

import com.ncmmall.application.business.goods.GoodsAttributeChannelApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.attribute.GoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.GoodsAttributeChannel;
import com.ncmmall.domain.business.goods.attribute.GoodsAttributeChannelRelevancy;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttribute;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttributeChannel;
import com.ncmmall.domain.business.goods.attribute.QGoodsAttributeChannelRelevancy;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.mall.params.ParamsDTO;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * 商品规格类目管理
 */
@Controller
@RequestMapping(value = "/mall/goods/attribute/channel")
public class AttributeChannelController {

    private final static Logger logger = LoggerFactory.getLogger(AttributeChannelController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private GoodsAttributeChannelApplication attributeApplication;

    @Autowired
    private OperationLogApplication logApplication;

    /**
     * 商品规格类目管理列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, GoodsAttributeChannel attributeChannel) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from GoodsAttributeChannel u where 1=1 ", params, attributeChannel);
        QueryPage<GoodsAttributeChannel> page = queryChannelService.findPage(hql, pageRequest.setParams(params), GoodsAttributeChannel.class);
        model.addAttribute("page", page).addAttribute("params", attributeChannel);

        return "mall/goods/attribute/channel/list";
    }

    /**
     * 添加规格类目页面
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {
        GoodsAttributeChannel attributeChannel = new GoodsAttributeChannel();
        model.addAttribute("_method", "POST").addAttribute("attribute", attributeChannel);

        return "mall/goods/attribute/channel/form";
    }

    /**
     * 添加规格类目
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, GoodsAttributeChannel attributeChannel) {
        String name = attributeChannel.getName();

        int count = queryChannelService.selectCount("select count(*) from mall_goods_attribute_channel where name = :name",
                ImmutableMap.of("name", attributeChannel.getName()));
        if (count > 0) {
            return ImmutableMap.of("status", false, "message", "规格类目名称已存在");
        }

        attributeApplication.create(attributeChannel);
        logApplication.eventOfSystem(Securitys.currentUser(), "添加平台规格类目", Securitys.getIp(request));
        return ImmutableMap.of("status", true);
    }

    /**
     * 编辑规格类目页面
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    private String modify(Model model, @PathVariable("id") long id) {

        GoodsAttributeChannel attributeChannel = queryChannelService.findOne(QGoodsAttributeChannel.goodsAttributeChannel.id.eq(id), GoodsAttributeChannel.class);

        model.addAttribute("_method", "PUT").addAttribute("attribute", attributeChannel);

        return "mall/goods/attribute/channel/form";
    }


    /**
     * 修改规格类目
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, GoodsAttributeChannel attributeChannel) {

        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            attributeApplication.modify(attributeChannel);
            logApplication.eventOfSystem(Securitys.currentUser(), "修改平台规格类目", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 关联规格类目页面
     */
    @RequestMapping(value = "/{id}/connection", method = RequestMethod.GET)
    private String connection(Model model, @PathVariable("id") long id) {

        GoodsAttributeChannel attributeChannel = queryChannelService.findOne(QGoodsAttributeChannel.goodsAttributeChannel.id.eq(id), GoodsAttributeChannel.class);
        List<GoodsAttributeChannelRelevancy> relevancies = queryChannelService.findAll(QGoodsAttributeChannelRelevancy.goodsAttributeChannelRelevancy.channel.id.eq(id), GoodsAttributeChannelRelevancy.class);

        model.addAttribute("_method", "PUT").addAttribute("attributeChannel", attributeChannel).addAttribute("relevancies", relevancies);

        return "mall/goods/attribute/channel/connection";
    }

    @RequestMapping(value = "/relevancy", method = RequestMethod.GET)
    private String relevancy(Model model, @RequestParam("id") long id) {
        GoodsAttributeChannel attributeChannel = queryChannelService.findOne(QGoodsAttributeChannel.goodsAttributeChannel.id.eq(id), GoodsAttributeChannel.class);
        List<GoodsAttribute> attributes = queryChannelService.findAll(QGoodsAttribute.goodsAttribute.type.eq(1).and(QGoodsAttribute.goodsAttribute.parent.isNull()), GoodsAttribute.class);
        model.addAttribute("attributeChannel", attributeChannel).addAttribute("attributes", attributes);
        return "mall/goods/attribute/channel/relevancy";
    }

    /**
     * 关联规格类目分类
     */
    @RequestMapping(value = "/relevancy", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> relevancy(ParamsDTO params) {
        try {
            attributeApplication.relevancy(params.getId(), params.getIds());
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 删除规格类目
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsAttributeChannel attributeChannel = queryChannelService.findOne(QGoodsAttributeChannel.goodsAttributeChannel.id.eq(id), GoodsAttributeChannel.class);

            attributeApplication.remove(attributeChannel);
            logApplication.eventOfSystem(Securitys.currentUser(), "删除平台规格类目", Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false);
        }


    }

    /**
     * 删除关联
     */
    @RequestMapping(value = "/removeRelevancy", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> removeRelevancy(@RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            GoodsAttributeChannelRelevancy attributeChannel = queryChannelService.findOne(QGoodsAttributeChannelRelevancy.goodsAttributeChannelRelevancy.id.eq(id), GoodsAttributeChannelRelevancy.class);

            attributeApplication.removeRelevancy(attributeChannel);

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            logger.error("[权限删除异常]", e);
            return ImmutableMap.of("status", false);
        }


    }

    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, GoodsAttributeChannel attribute) {

        if (!Strings.isNullOrEmpty(attribute.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + attribute.getName() + "%");
        }

        return sql;
    }


}
